﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Configuration;
using Activity.Comm;
using Activity.Data;

namespace Activity.API
{
    public class BaseLottery
    {
        /// <summary>
        /// 使用的Redis数据库索引
        /// </summary>
        public const int RedisDatabaseIndex = 4;
        /// <summary>
        /// 测试
        /// </summary>
        static readonly string isDebug = WebConfigurationManager.AppSettings["isDebug"];

        public static object obj = new object();
        /// <summary>
        ///  检验活动时间
        /// </summary>
        /// <param name="_baseBeginDate"></param>
        /// <param name="_baseEndDate"></param>
        /// <returns></returns>
        public bool CheckDate(DateTime _baseBeginDate,DateTime _baseEndDate)
        {
            if (DateTime.Now < _baseBeginDate && isDebug.ToLower() == "false")
            {
                return false;
            }
            if (DateTime.Now > _baseEndDate && isDebug.ToLower() == "false")
            {
                return false;
            }
            return true;
        }

        /// <summary>
        /// 检查用户是否会员
        /// </summary>
        /// <param name="openId"></param>
        /// <returns></returns>
        public bool CheckUser(string openId)
        {
            var dc = new HKERPEntities();
            return dc.KM_V_CardBinding.Any(t => t.OpenID == openId);
        }

        /// <summary>
        /// 检查用户是否会员，成功返回用户积分
        /// </summary>
        /// <param name="openId"></param>
        /// <returns></returns>
        public LotteryUserInfo GetUserIntegral(string openId)
        {
            var dc = new HKERPEntities();
            var result = (from c in dc.KM_V_CardBinding
                join m in dc.CRM_Bas_CardInfo on c.CardID equals m.CardID
                where c.OpenID == openId
                select new
                {
                    c.OpenID,
                    c.CardID,
                    m.RemainIntegral
                }).ToList().Select(o => new LotteryUserInfo()
            {
                OpenID = o.OpenID,
                CardID = o.CardID,
                TotalIntegral = o.RemainIntegral
            }).FirstOrDefault();
            return result;
        }

        /// <summary>
        /// 生成奖项
        /// </summary>
        /// <param name="dict">奖池</param>
        /// <returns></returns>
        public int BuildLoggeryInfo(Dictionary<string, double> dict)
        {
            if (dict == null) return -1;
            var list = new List<double>(dict.Values);
            //var gifts = new List<string>(map.Keys);
            var method = new AliasMethod(list);
            return method.Next();
        }

        /// <summary>
        /// 获取券号，14位，含数字字母随机生成，建议KM开头
        /// </summary>
        /// <returns>指定长度的随机字符串</returns>
        public string GetTHQNo()
        {
            string strSep = ",";
            char[] chrSep = strSep.ToCharArray();
            string strChar = "0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z";
            string[] aryChar = strChar.Split(chrSep, strChar.Length);
            string strRandom = string.Empty;

            var Rnd = new Random((int)DateTime.Now.Ticks);
            //生成随机字符串
            for (int i = 0; i < 12; i++)
            {
                strRandom += aryChar[Rnd.Next(aryChar.Length)];
            }
            return "KM" + strRandom;
        }

        /// <summary>
        /// 把生成的红包卡券保存到恒康ERP库
        /// </summary>
        /// <param name="OpenId">微信对应用户唯一OpenId</param>
        /// <param name="CardCode">CardCode=红包卡编号=三种金额的优惠券对应固定的ERP内码</param>
        /// <param name="CardType">卷类型：1=10、2=20、3=66.6</param>
        public void SaveRedPacHKERP(string OpenId, string CardCode, int CardType, string THQNo)
        {
            try
            {
                if (isDebug.ToLower() == "false")
                {
                    string BillNo = "THQPr" + DateTime.Now.ToString("yyMMdd") + "KM01-001";
                    using (var dc = new HKEntities())
                    {
                        var query = dc.KM_V_CardBinding.FirstOrDefault(t => t.OpenID == OpenId);
                        string CustomerID = query.CustomerID;
                        string THQID = CardCode;
                        DateTime UseStartDate = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd"));
                        DateTime UseEndDate = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd") + " 23:59:59");
                        decimal Amount = 0;
                        if (CardType == 2)
                        {
                            Amount = 10;
                        }
                        else if (CardType == 3)
                        {
                            Amount = Convert.ToDecimal(66.6);
                        }
                        else
                        {
                            Amount = 5;
                        }

                        string insertSql = @"INSERT INTO [dbo].[Crm_Bas_THQDetail]
           ([CompanyID]
           ,[BillNo]
           ,[CustomerID]
           ,[THQID]
           ,[UseStartDate]
           ,[UseEndDate]
           ,[MiniAmounts]
           ,[Amount]
           ,[THQNo]
           ,[THQStatus]
           ,[PromoteTypeID]
           ,[WXPublicNo]
           ,[WXOpenID]
           ,[PromoteDate]
           ,[PromoteState]
           ,[ModifyDTM]
           ,[Sequence]
           ,[BillTypeID]
           ,[THQRuleType]
           ,[OldCustomerID]
           ,[StatusRemark]
           ,[PromoteUserID]
           ,[ISWX_HK])
     VALUES
           ('KM','{0}','{1}','{2}','{3}','{4}',{5},{6},'{7}','1','0','','{8}',GETDATE(),'0',GETDATE(),'','Crm_CardRegDef','1',null,null,null,null) ";
                        insertSql = string.Format(insertSql, BillNo, CustomerID, THQID, UseStartDate, UseEndDate,
                            Amount, Amount, THQNo, OpenId);
                        var insertNum = dc.Database.ExecuteSqlCommand(insertSql);
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}
